/*问题设想：
* 1、遍历比较——插入(将l1插入到l2中)
* 2、将其比较后插入新链表*/
class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    public static ListNode creatLink(int[] num){
          if (num.length == 0){
              return null;
          }
        ListNode Head = new ListNode(num[0]);
        ListNode cur = Head;
        for (int i = 1; i < num.length; i++) {
            ListNode listNode = new ListNode(num[i]);
            cur.next = listNode;
            cur = listNode;
        }
        return Head;
    }
}
class Solution {
    //如果两个链表为空的情况？
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = list2;
        if (list1==null){
            return list2;
        }else if (list2==null){
            return list1;
        }
        while (list1 != null){
            if (list1.val <= list2.val){
                ListNode l1next = list1.next;
                Solution.add(list1,list2);
                list2 = list2.next;
                list1 = l1next;
            }else {
                if (list2.next == null){
                    add(list1,list2);
                }
                list2 = list2.next;
            }
        }
        return head;
    }
    //将l1插入到l2的后面
    public static void add(ListNode l1,ListNode l2){
        ListNode l2next = l2.next;
        l2.next = l1;
        l1.next = l2next;
    }
    public static void display(ListNode head){
        ListNode cur = head;
        while (cur != null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
    }
    public static void main(String[] args) {
        int[] num1 = {5,2,4};
        int[] num2 = {1,3,4};
        ListNode l1 = ListNode.creatLink(num1);
        ListNode l2 = ListNode.creatLink(num2);
        Solution.display(Solution.mergeTwoLists(l1,l2));

    }
}